package com.data.modules.smzh.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.data.common.api.vo.Result;
import com.data.common.constant.enums.ProductEnum;
import com.data.common.util.HttpClientUtil;
import com.data.common.util.KamliClientUtil;
import com.data.modules.gd.vo.CityRankVo;
import com.data.modules.gd.vo.DataVo;
import com.data.modules.smzh.entity.Building;
import com.data.modules.smzh.entity.SmDeviceVersion;
import com.data.modules.smzh.entity.SmThirdRegist;
import com.data.modules.smzh.mapper.SmDeviceVersionMapper;
import com.data.modules.smzh.service.IBuildingService;
import com.data.modules.smzh.service.ISmDeviceVersionService;
import com.data.modules.smzh.entity.SmDeviceVersion;
import com.data.modules.smzh.service.ISmDeviceVersionService;
import com.data.modules.smzh.service.ISmThirdRegistService;
import com.data.modules.system.entity.SysCategory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 设备版本信息
 * @Author: data-boot
 * @Date:   2023-03-23
 * @Version: V1.0
 */
@Service
@Slf4j
public class SmDeviceVersionServiceImpl extends ServiceImpl<SmDeviceVersionMapper, SmDeviceVersion> implements ISmDeviceVersionService {

    @Autowired
    private SmDeviceVersionMapper versionMapper;
    @Autowired
    private IBuildingService buildingService;

    @Autowired
    private ISmThirdRegistService thirdRegistService;

    @Value("${lqh.registerUrl:}")
    private String thirdUrl;

    @Override
    public Result<?> updateResultInfo(SmDeviceVersion deviceVersion) {
        //通过 序列号+设备类型 查询是否有数据
        try {

            LambdaQueryWrapper<SmDeviceVersion> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SmDeviceVersion::getModel,deviceVersion.getModel());
            queryWrapper.eq(SmDeviceVersion::getSerialNo,deviceVersion.getSerialNo());

            SmDeviceVersion vo = this.baseMapper.selectOne(queryWrapper);
            if(ObjectUtil.isNotEmpty(vo)){
                if(ObjectUtil.isNotEmpty(deviceVersion.getVersion())){
                    vo.setVersion(deviceVersion.getVersion());
                }

                if(ObjectUtil.isNotEmpty(deviceVersion.getImei())){
                    vo.setImei(deviceVersion.getImei());
                }

                if(ObjectUtil.isNotEmpty(deviceVersion.getIccId())){
                    vo.setIccId(deviceVersion.getIccId());
                }

                if(ObjectUtil.isNotEmpty(deviceVersion.getSn())){
                    vo.setSn(deviceVersion.getSn());
                }

                this.baseMapper.updateById(vo);
            }else{

                if(ProductEnum.SMW_721X10.getCode().equals(deviceVersion.getModel()) && ObjectUtil.isNotEmpty(deviceVersion.getSn())){
                    //sn 进行龙侨华注册操作
                    Map<String,Object> map = new HashMap<>();
                    map.put("username",deviceVersion.getSn());
                    map.put("password","123456");
                    map.put("origin","2001");

                    //调用第三方接口
                    String result = HttpClientUtil.doPostJson(thirdUrl, JSON.toJSONString(map));

                    if(ObjectUtil.isNotEmpty(result)){

                        JSONObject jsonObject = JSONObject.parseObject(result);

                        String code = jsonObject.getString("code");
                        log.info("调用龙侨华注册接口请求参数{},结果{}",JSON.toJSONString(map),code);
                        if(ObjectUtil.equals("1",code) || ObjectUtil.equals("7",code)){
                            deviceVersion.setRemark(result);
                        }
                    }
                }

                this.baseMapper.insert(deviceVersion);

            }
        } catch (Exception e) {

            return Result.error(e.getMessage());
        }

        return Result.OK();
    }

    @Override
    public Result<?> updateV2ResultInfo(SmDeviceVersion deviceVersion) {
        //通过 序列号+设备类型 查询是否有数据
        try {

            LambdaQueryWrapper<SmDeviceVersion> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SmDeviceVersion::getModel, deviceVersion.getModel());
            queryWrapper.eq(SmDeviceVersion::getSn, deviceVersion.getSn());

            SmDeviceVersion vo = this.baseMapper.selectOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(vo)) {
                if (ObjectUtil.isNotEmpty(deviceVersion.getVersion())) {
                    vo.setVersion(deviceVersion.getVersion());
                }

                if (ObjectUtil.isNotEmpty(deviceVersion.getLatitude())) {
                    vo.setLatitude(deviceVersion.getLatitude());
                }

                if (ObjectUtil.isNotEmpty(deviceVersion.getLongitude())) {
                    vo.setLongitude(deviceVersion.getLongitude());
                }
                if (ObjectUtil.isNotEmpty(deviceVersion.getCity())) {
                    vo.setCity(deviceVersion.getCity());
                }
                if (ObjectUtil.isNotEmpty(deviceVersion.getMirrorVersion())) {
                    vo.setMirrorVersion(deviceVersion.getMirrorVersion());
                }

                this.baseMapper.updateById(vo);
            } else {

                this.baseMapper.insert(deviceVersion);
                //创建sip账号
                // KamliClientUtil.doPost(deviceVersion.getSn(),"PvUdG1");
                KamliClientUtil.doPost(deviceVersion.getSn(),"870830");

            }
        } catch (Exception e) {

            return Result.error(e.getMessage());
        }

        return Result.OK();
    }

    @Override
    public Map queryTodayTvInfo() {

        Map<String,Object> map = new HashMap<>();

        List<DataVo> list =versionMapper.searchTodayTvInfo();
        map.put("click",list.size());
        BigDecimal costTime = list.stream().map(DataVo::getCost).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String,Long> snMap = list.stream().filter(x->ObjectUtil.isNotEmpty(x.getSn())).collect(Collectors.groupingBy(DataVo::getSn,Collectors.counting()));

        BigDecimal size = new BigDecimal(snMap.size()*60);
        map.put("avgTime",costTime.divide(size,2,BigDecimal.ROUND_HALF_UP));

        List<CityRankVo> userList  = list.stream().filter(x->ObjectUtil.isNotEmpty(x.getCity())).collect(Collectors.groupingBy(DataVo::getCity,Collectors.counting())).entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).map(a -> new CityRankVo(a.getKey(),a.getValue())).collect(Collectors.toList());

        map.put("city",userList.get(0).getCity());
        return map;
    }

    @Override
    public List<Map> querySevenDayTvInfo() {
        return versionMapper.searchSevendayTvInfo();
    }

    @Override
    public List<Map> querySevenDayChannelData() {
        return versionMapper.searchSevendayChannel();
    }

    @Override
    public List<CityRankVo> getNearSevenAllData() {
        Map<String,Object> map = new HashMap<>();

        List<DataVo> list =versionMapper.searchSevenTodayAllInfo();

        List<CityRankVo> userList  = list.stream().filter(x->ObjectUtil.isNotEmpty(x.getCity())).collect(Collectors.groupingBy(DataVo::getCity,Collectors.counting())).entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).map(a -> new CityRankVo(a.getKey(),a.getValue())).collect(Collectors.toList());

        return userList;
    }

    @Override
    public List<Map> getNearSevenClickData() {

        return versionMapper.searchSevenClickData();
    }

    @Override
    public List<Map> getSdTimeAndType() {

        return versionMapper.searchSdTimeAndType();
    }

    @Override
    public List<CityRankVo> queryAreaData() {

        Map<String,Object> map = new HashMap<>();

        List<DataVo> list =versionMapper.searchSevenTodayAllInfo();
        map.put("click",list.size());
        BigDecimal total = new BigDecimal(list.size());

        List<CityRankVo> userList  = list.stream().filter(x->ObjectUtil.isNotEmpty(x.getCity())).collect(Collectors.groupingBy(DataVo::getCity,Collectors.counting())).
                entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
                .map(a -> {
                    CityRankVo vo =  new CityRankVo();
                    vo.setCity(a.getKey());
                    vo.setTotal(Long.valueOf(list.size()));
                    BigDecimal result = new BigDecimal(a.getValue()).multiply(new BigDecimal(100)).divide(total,2,BigDecimal.ROUND_HALF_UP);
                    vo.setRate(result);
                    return  vo;
                }).collect(Collectors.toList());

        return userList;
    }

}

